import urllib.request
import json
import time
import pandas as pd

def get_url(code, cycle, num):
    url = "https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=%s&scale=%d&ma=no&datalen=%d"%(code, cycle, num)
    return url
def get_cur_url(code):
    url = "http://hq.sinajs.cn/list=%s"%(code)
    return url
def get_time():
    timeArray = time.localtime()
    return time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
def get_hours():
    timeArray = time.localtime()
    return int(time.strftime("%H", timeArray))
def get_mins():
    timeArray = time.localtime()
    return int(time.strftime("%M", timeArray))
def get_week():
    timeArray = time.localtime()
    return int(time.strftime("%w", timeArray))
def get_url_data(url):
    resp = urllib.request.urlopen(url)
    data = resp.read()
    data_json = json.loads(data)
    return data_json
def get_url_strdata(url):
    resp = urllib.request.urlopen(url)
    data = resp.read()
    return str(data)
def work_time_check():
    hours = get_hours()
    mins = get_mins()
    week = get_week()
    am = hours*60 + mins
    # print("hours=", hours, "mins=", mins, "am=", am, "week=", week)
    if week < 1 or week > 5:
        return False
    # 09:30~11:30
    if am >= 9*60+30 and am <= 11*60+30:
        return True
    # 13:00~15:00
    if am >= 13*60 and am <= 15*60:
        return True
    return False
def get_kdj_data(data):
    df = pd.DataFrame()
    da = []
    for v in data:
        t = {"low":float(v["low"]), "high":float(v["high"]), "close":float(v["close"]), "open":float(v["open"])}
        df = df.append(t, ignore_index=True)
        da.append(v["day"])
    df.index = da
    low_list = df['low'].rolling(9, min_periods = 9).min()
    low_list.fillna(value = df['low'].expanding().min(), inplace = True)
    high_list = df['high'].rolling(9, min_periods=9).max()
    high_list.fillna(value = df['high'].expanding().max(), inplace = True)

    rsv = (df['close'] - low_list) / (high_list - low_list) * 100
    # print("rsv", rsv)
    df['K'] = pd.DataFrame(rsv).ewm(com=2,adjust=False).mean()
    df['D'] = df['K'].ewm(com=2,adjust=False).mean()
    df['J'] = 3 * df['K'] - 2 * df['D']

    return df

def get_codes():
    codes = []
    for i in range(300000, 300000 + 1000):
        code = "sz%.6d"%(i)
        codes.append(code)

    return codes